package com.example.pacs.service.impl;

import com.example.pacs.bean.request.QueryParamsRequest;
import com.example.pacs.constants.PacsConstants;
import com.example.pacs.dao.DicomServerMapper;
import com.example.pacs.dicom.server.cmove.InstanceLocators;
import com.google.common.collect.Lists;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;

@Service
public class DicomServerService implements com.example.pacs.service.DicomServerService {

    @Resource
    private DicomServerMapper dicomServerMapper;

    @Value("${pacs.storage.dir}")
    private String pacsStorageDir;

    @Override
    public List<InstanceLocators> cmoveQuery(QueryParamsRequest params) {
        List<InstanceLocators> instanceLocators = Lists.newArrayList();
        List<Long> seriesId = dicomServerMapper.queryStudyAndSeries(params);
        if (!CollectionUtils.isEmpty(seriesId)) {
            instanceLocators = dicomServerMapper.queryInstanceBySeriesId(seriesId);
            if (!CollectionUtils.isEmpty(instanceLocators)) {
                for (InstanceLocators locator : instanceLocators) {
                    try {
                        URI uri = new URI(pacsStorageDir + "/" + locator.getMediaStorageSopInstanceUid() + PacsConstants.DCM_SUFFIX);
                        locator.setUri(uri.toString());
                    } catch (URISyntaxException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return instanceLocators;
    }
}
